package com.heng.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.heng.dao.entity.user.UserEntity;
import com.heng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 1. 新增用户（POST）
    @PostMapping
    public boolean addUser(@RequestBody UserEntity userEntity) {
        return userService.save(userEntity);
    }

    // 2. 根据ID删除用户（DELETE）- 逻辑删除需配置全局参数
    @DeleteMapping("/{userId}")
    public boolean deleteUser(@PathVariable("userId") Long userId) {
        return userService.removeById(userId);
    }

    // 3. 更新用户信息（PUT）
    @PutMapping
    public boolean updateUser(@RequestBody UserEntity userEntity) {
        return userService.updateById(userEntity);
    }

    // 4. 根据ID查询用户（GET）
    @GetMapping("/{userId}")
    public UserEntity getUserById(@PathVariable("userId") Long userId) {
        try {
            UserEntity userEntity = userService.getById(userId);
            System.out.println(userEntity);
            return userEntity;
        } catch (Exception e) {
            throw new RuntimeException("" + e.getMessage());
        }
    }

    // 5. 分页查询用户（GET）
    @GetMapping("/page")
    public IPage<UserEntity> pageQuery(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        return userService.pageQuery(pageNum, pageSize);
    }

    @GetMapping("/test")
    public String test() {
        return "userService.pageQuery(pageNum, pageSize);";
    }

    // 6. 按手机号查询用户（GET）
    @GetMapping("/phone/{phone}")
    public UserEntity getUserByPhone(@PathVariable String phone) {
        return userService.getByPhone(phone);
    }
}